﻿package net.wangit.dev.component;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.dev.LabelRule;
import net.wangit.dev.ReferenceUtil;
import net.wangit.jdbc.DB;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

public class TreeTree extends ObjectTree {

	private static final String PREFIX = "_04C";
	private static final String TYPE = Integer.toString(4);
	private static final String TREE_SQL = "select tid,tn,l,gid from TREECONFIG order by o,tid";
	private static final String COUNT_NAME = "rowcount";
	private static final String ITEM_SQL = "select count(*) rowcount from TREE where tid=?";

	public TreeTree() {
	}

	protected String getItemsTableName() {
		return "TREE";
	}

	protected String getComponentType() {
		return TYPE;
	}

	protected MapList getObjects(DB db) throws Exception {
		MapList objects = db.query(TreeTree.TREE_SQL);
		objectCount = Checker.isEmpty(objects) ? 0 : objects.size();
		return objects;
	}

	protected boolean showNullGroup() {
		return true;
	}

	protected String getGroupAttribute() {
		return "oncontextmenu=wmg4()";
	}

	protected int addObject(ActionContext ac, DB db, Tree parent, Row row)
			throws Exception {
		int itemCount = 0;
		Tree object = new Tree();
		String id = row.get("tid");
		object
				.setId((new StringBuilder(TreeTree.PREFIX)).append(id)
						.toString());
		String name = row.get("tn");
		String status = row.get("l", "0");
		object.setIcon((new StringBuilder("/domain/dev/c/tree")).append(status)
				.append(".png").toString());
		if (check) {
			name = (new StringBuilder(String.valueOf(id))).append(" ").append(
					name).toString();
		} else {
			int referenceCount = ReferenceUtil.getReferenceCount(db, Integer
					.toString(85), id);
			itemCount = getItemCount(db, id);
			String label = LabelRule.getLabel(ac, ObjectTreeHelper
					.getLableRule(ac), id, name);
			name = (new StringBuilder(String.valueOf(referenceCount))).append(
					" ").append(label).append(" ").append(itemCount).toString();
			object.setAttribute("oncontextmenu=wm4()");
			object.setAction((new StringBuilder("/dev/tree.do?m=e&treeid="))
					.append(id).toString());
		}
		object.setName(name);
		parent.add(object);
		return itemCount;
	}

	public static int getItemCount(DB db, String id) throws Exception {
		MapList list = db.query(TreeTree.ITEM_SQL, id, 2);
		return list.getRow(0).getInt(TreeTree.COUNT_NAME, 0);
	}

}
